package com.kefu.chat.service;

import java.io.File;
import java.io.FileInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kefu.chat.model.ChatAdmin;
import com.kefu.chat.model.ChatChannel;
import com.kefu.chat.model.ChatUser;
import com.kefu.chat.util.ChatConstant;
import com.kefu.chat.vo.ChatUserParam.UserConnectP;
import com.kefu.chat.vo.ChatUserParam.UserConnectR;
import com.kefu.chat.vo.ChatUserParam.UserRobotAskP;
import com.kefu.chat.vo.ChatUserParam.UserRobotAskR;
import com.kefu.chat.vo.ChatUserParam.UserSendMsgP;
import com.kefu.common.multipart.IMultipartProvider;
import com.kefu.common.multipart.MultiPart;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Singleton;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HtmlUtil;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;

@Service
public class ChatWxMiniService {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ChatChannelService chatChannelService;
    @Autowired
    private ChatUserService chatUserService;
    @Autowired
    private ChatRobotService chatRobotService;
    @Autowired
    private ChatCacheService chatCacheService;
    @Autowired
    private IMultipartProvider multipartProvider;

    public WxMaService getWxMaService(String appId) {
        ChatChannel channel = chatChannelService.getFromAppId(appId);
        WxMaService wxMaService = Singleton.get(WxMaServiceImpl.class);
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(channel.getAppId());
        config.setSecret(channel.getAppSecret());
        config.setToken(channel.getAppToken());
        config.setAesKey(channel.getAesKey());
        config.setMsgDataFormat(channel.getMsgDataFormat());
        wxMaService.addConfig(appId, config);
        return wxMaService.switchoverTo(appId);
    }

    public void eventHandle(String appId, WxMaMessage inMessage) {
        logger.info("wx_eventHandle:{}", inMessage);
    }

    public void msgHandle(String appId, WxMaMessage inMessage) {
        try {
            ChatChannel channel = chatChannelService.getFromAppId(appId);
            if (channel == null) {
                return;
            }
            WxMaService wxMaService = getWxMaService(appId);
            int receiveMode = channel.getReceiveMode();
            String tenantId = channel.getTenantId();
            String userPid = inMessage.getFromUser();
            String userId = SecureUtil.md5(tenantId + userPid);
            String msgType = inMessage.getMsgType();
            String content = inMessage.getContent();
            boolean robotAsk = false;
            boolean adminConnect = false;
            boolean adminMsg = false;
            ChatUser user = chatCacheService.getUser(userId);
            if (user == null || user.getStatus() == ChatConstant.user_status_offline) {
                ChatUser newUser = new ChatUser();
                newUser.setSessionId(IdUtil.simpleUUID());
                newUser.setUserId(userId);
                newUser.setPid(userPid);
                newUser.setTenantId(tenantId);
                newUser.setChannelId(channel.getChannelId());
                newUser.setChannelType(ChatConstant.channel_type_wx_mini);
                newUser.setChannelName(channel.getChannelName());
                newUser.setAppId(appId);
                newUser.setUserName("小程序客户");
                if (user != null) {
                    newUser.setPhone(user.getPhone());
                    newUser.setEmail(user.getEmail());
                    newUser.setCustomerId(user.getCustomerId());
                    newUser.setLastAdminId(user.getAdminId());
                    newUser.setUserFormMode(user.getUserFormMode());
                }
                user = newUser;
                chatCacheService.setUser(user);
                if (receiveMode == ChatConstant.chat_receive_robot_first || receiveMode == ChatConstant.chat_receive_robot_only) {
                    robotAsk = true;
                } else if (receiveMode == ChatConstant.chat_receive_admin_first || receiveMode == ChatConstant.chat_receive_admin_only) {
                    adminConnect = true;
                }
            } else if (user.getStatus() == ChatConstant.user_status_robot) {
                robotAsk = true;
            } else if (user.getStatus() == ChatConstant.user_status_wait) {
                if (receiveMode != ChatConstant.chat_receive_admin_only) {
                    robotAsk = true;
                }
            } else if (user.getStatus() == ChatConstant.user_status_online) {
                adminMsg = true;
            }
            if ("人工".equals(content) || "转人工".equals(content)) {
                if ((user.getStatus() == ChatConstant.user_status_offline || user.getStatus() == ChatConstant.user_status_robot) && receiveMode != ChatConstant.chat_receive_robot_only) {
                    adminConnect = true;
                }
            }
            if (adminConnect) {
                UserConnectP connectParam = new UserConnectP();
                connectParam.setUserId(userId);
                UserConnectR connectResult = chatUserService.connect(connectParam);
                if (connectResult.getStatus() == 1) {
                    if (receiveMode == ChatConstant.chat_receive_admin_only) {
                        wxMaService.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content(channel.getAdminOfflineMsg()).toUser(inMessage.getFromUser()).build());
                    } else {
                        robotAsk = true;
                    }
                }
                if (connectResult.getStatus() == 2) {
                    adminMsg = true;
                }
                if (connectResult.getStatus() == 3) {
                    if (receiveMode != ChatConstant.chat_receive_admin_only) {
                        robotAsk = true;
                    }
                }
            }
            if (adminMsg) {
                UserSendMsgP msgParam = new UserSendMsgP();
                msgParam.setUserId(userId);
                if (WxMaConstants.KefuMsgType.TEXT.equals(msgType)) {
                    msgParam.setMsgType(ChatConstant.chat_msg_type_text);
                    msgParam.setMsgContent(content);
                } else if (WxMaConstants.KefuMsgType.IMAGE.equals(msgType)) {
                    msgParam.setMsgType(ChatConstant.chat_msg_type_image);
                    File file = wxMaService.getMediaService().getMedia(inMessage.getMediaId());
                    MultiPart multiPart = multipartProvider.upload(new FileInputStream(file), "wx", tenantId, "jpg");
                    msgParam.setMsgContent(multiPart.getUrl());
                } else {
                    wxMaService.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("【不支持的消息类型】").toUser(inMessage.getFromUser()).build());
                    return;
                }
                chatUserService.sendMsg(msgParam);

            }
            if (robotAsk) {
                if (WxMaConstants.KefuMsgType.TEXT.equals(msgType)) {
                    UserRobotAskP robotParam = new UserRobotAskP();
                    robotParam.setUserId(userId);
                    robotParam.setRobotNo(channel.getRobotNo());
                    robotParam.setQuestion(content);
                    UserRobotAskR robotResult = chatRobotService.userRobotAsk(robotParam);
                    StringBuilder robotAnswer = new StringBuilder();
                    if (StrUtil.isNotBlank(robotResult.getAnswer())) {
                        robotAnswer.append(robotResult.getAnswer());
                    }
                    for (int i = 0; i < robotResult.getSuggestList().size(); i++) {
                        robotAnswer.append("\n").append(i + 1).append(".").append(robotResult.getSuggestList().get(i).getQuestion());
                    }
                    wxMaService.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content(HtmlUtil.cleanHtmlTag(robotAnswer.toString())).toUser(inMessage.getFromUser()).build());
                } else {
                    wxMaService.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content(channel.getRobotUnknownMsg()).toUser(inMessage.getFromUser()).build());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String sendMsg(ChatAdmin admin, ChatUser user, int msgType, String msgContent) {
        try {
            WxMaService wxMaService = getWxMaService(user.getAppId());
            if (msgType == ChatConstant.chat_msg_type_text) {
                wxMaService.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content(HtmlUtil.cleanHtmlTag(msgContent)).toUser(user.getPid()).build());
            } else if (msgType == ChatConstant.chat_msg_type_image) {
                String path = multipartProvider.getPath(msgContent);
                WxMediaUploadResult uploadResult = wxMaService.getMediaService().uploadMedia(WxMaConstants.KefuMsgType.IMAGE, "jpg", FileUtil.getInputStream(path));
                wxMaService.getMsgService().sendKefuMsg(WxMaKefuMessage.newImageBuilder().mediaId(uploadResult.getMediaId()).toUser(user.getPid()).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "1";
    }

}
